package api

import (
	"fmt"
	"gitee.com/bishisimo/udesk/option"
	"github.com/go-resty/resty/v2"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
)

/**
 * @Description: UDesk的控制器，用来实例化与管理个体UDesk通信器
 */
type UDeskCtl struct {
	*uDeskCore `json:"udesk_core"` //UDesk配置信息
}

/**
 * @Description: 实例化UDesk方法
 * @receiver c
 * @param customerToken 客户的唯一标识
 * @return *UDesk
 */
func (c *UDeskCtl) NewUDesk(customerToken string) *UDesk {
	return newUDesk(c.uDeskCore, customerToken)
}

/**
 * @Description: 用UDesk邮箱和密码申请udesk的token
 * @receiver c
 * @return error
 */
func (c *UDeskCtl) RefreshToken() error {
	url := c.GetUDeskUrl("token")
	r := new(option.TokenResp)
	body := option.NewTokenOption(c.Email, c.Password)
	_, err := resty.New().R().SetBody(body).SetResult(r).Post(url)
	if err != nil || r.Code != option.SuccessCode {
		return errors.New(fmt.Sprintf("refresh udesk token fail:%v", r.Code))
	}
	c.UDeskToken = r.OpenApiAuthToken
	log.Debug().Str("token", c.UDeskToken).Msg("refresh toke success")
	return nil
}

/**
 * @Description: 使用option结构体初始化UDeskCtl
 * @param o 初始化UDesk的结构体
 * @return *UDeskCtl
 */
func NewUDeskCtlByOption(o *option.UDeskOption) *UDeskCtl {
	return &UDeskCtl{
		uDeskCore: &uDeskCore{
			UDeskOption: o,
		},
	}
}

/**
 * @Description: 使用参数实例化控制器，需要控制者获取token
 * @param email udesk的账户的邮箱
 * @param password udesk的账户的密码
 * @param domain udesk的账户的域名
 * @param api udesk路由的api前缀
 * @return *UDeskCtl
 */
func NewUDeskCtl(email string, password string, domain string, api string) *UDeskCtl {
	op := &option.UDeskOption{
		Email:    email,
		Password: password,
		Domain:   domain,
		Api:      api,
	}
	return NewUDeskCtlByOption(op)
}
